#coding=UTF-8
'''
#财务指标
@author: joseph
'''
import datetime
from constant.Constant import *;
from xlrd import open_workbook
from xlutils.save import save
from xlwt.Workbook import Workbook

old='zcfzb';#TODO
radio_names={};
url_sec='cwzb'#TODO
year=datetime.date.today().year;
month=def_month;
selected_month="";
#stocks=[300001];# for test

url = concatUrl(url_head,concatUrl(url_sec, url_sec))

#value="max_yyyy=2010&stockCode=300001&yyyy=2008&mm=-12-31&image.x=21&image.y=11";

#add paras to the url
def para(code,year,month=def_month):
#    max_year=datetime.date.today().year;
    if(year==datetime.date.today().year and (month==def_month or month==selected_month)):
        return paraCurrentYear(code)
    return "?stockCode="+str(code)+"&yyyy="+str(year)+"&mm="+str(month);#ignore "max_yyyy="+max_year

def paraCurrentYear(code):
    return "?stockCode="+str(code);


def findTypes(urlComplete,year,month=def_month,code=min_stock_code):
    u=urlComplete+para(code,year,month);
    soup = soupUrl(u);
    radios=soup.findAll('input',{'type':'radio'})
    o=soup.find('select',{'name':'mm'})
    options=o.findAll('option'); #季度报表
    sel=o.find('option',{'selected':'selected'})
    selected_month=sel['value'];
    y_options=soup.find('select',{'name':'yyyy'}).findAll('option'); #年份
#    selected=False;
    for op in options:

#        if(False==selected and op != o.find('select'),{'selected':'selected'}):
#            continue;
#        else:
            #if('selected' in op and 'selected'==op['selected']):
            #selected=True
        period.append(op['value'])
        periodMap[op['value']]=op.next.strip();
    for y_op in y_options:
        years.append(int(y_op['value']));
    years.sort();
    for radio in radios:
        radio_names[radio['value']]=radio.next.strip();
    return selected_month
#return False if there are no data found        
def addRow(sheet,row=0,code=min_stock_code,type='right'):
    u=urlComplete+para(code,year,month);#add parameters in year
    soup = soupUrl(u);
    dataForm = soup.find('table',{'cellspacing':'1','cellpadding':'4'})
    col=0;
    sheet.write(row,col,code);
    if(dataForm==None):
        return False;
    datas=dataForm.findAll('div',{'align':type});
    for d in datas:
        col=col+1;
        sheet.write(row,col,str(d.text.encode(encode)));
    return True;

def addSheet(sheet):
    if(False==addRow(sheet,0,min_stock_code,'left')):#add title'股票代码'
        return False;
    row=1;
    for code in stocks:
        addRow(sheet, row, code);#add data
        row=row+1;
    return True;
    
#财务指标
#book=Workbook("utf-8");
currentYear=datetime.date.today().year;
#for y in range(currentYear,currentYear-3,-1): #近3年报表
#year=y;
#sheetCount=0;
urlComplete=url+'_'+old+suffix;
period=[]
selected_month=findTypes(urlComplete,currentYear);
#    if(y==currentYear):#when it's current year,there should be multiple tables besides the annual report
#        p=period;
#    else:
#        p=[period[0]];
p=period;
p.index;
for season in p:
    book=Workbook("utf-8");
    month=season;
    sheetUnavailable=True;
    sheetCount=0;
    for y in years: #range(currentYear-2,currentYear+1,1): #近3年报表
        year=y; 
        for k in radio_names.keys():
            if(None==k):
                continue;
            urlComplete=url+'_'+k+suffix;
            name=str(y)+radio_names[k]+periodMap[season]+u'报';
    #            name=name.encode(encode);
            if(sheetUnavailable):
                print(name);
                newSheet=book.add_sheet(name);
                sheetCount+=1;
            else:
                newSheet=book.get_sheet(sheetCount-1);
                newSheet.set_name(name)
            sheetUnavailable=addSheet(newSheet);#return false if there is no data in the page
            if(False==sheetUnavailable):
                #book.get_sheet(sheetCount-1);
                break;
    book.save(periodMap[season]+u'报'+u"财务指标.xls");

#重要经营指标
